package com.wlts.wzy.LoginController;

import com.alibaba.fastjson.JSONObject;
import com.wlts.wzy.LoginController.loginParm.LoginParm;
import com.wlts.wzy.Result.Result;
import com.wlts.wzy.api.request.ks.LoginKsUserRequest;
import com.wlts.wzy.util.MD5;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


/**
 * <p>
 * 系统用户登录 前端控制器
 * </p>
 *
 * @author wuzhiyong
 * @since 2019-05-30
 */
@Api(tags = "总管理用户登录接口")
@RestController
@RequestMapping("/SysLogin")
public class SysLoginController {
    /**
     * 登录接口
     */
    @PostMapping("AdminLogin")
    @ApiOperation(value = "登录接口")
    public Result AdminLogin(@RequestBody LoginKsUserRequest loginParm) {
        //System.out.println(sysUser.toString());
        JSONObject json = new JSONObject();
        String name = loginParm.getName();
        String pass = loginParm.getPassword();
        String passtheword = "";
        System.out.println(MD5.md5(pass, ""));
        try {
            passtheword = MD5.md5(pass, "");
        } catch (Exception e) {
            e.printStackTrace();
        }
        //查询数据库
        Subject subject = SecurityUtils.getSubject();
        //判断当前的subject是否登录
        //    if (!subject.isAuthenticated()){
        UsernamePasswordToken token = new UsernamePasswordToken(name, passtheword);
        try {
            //将存有用户名和密码的token存进subject中
            subject.login(token);
        } catch (UnknownAccountException uae) {
            json.put("message", "没有用户名为" + token.getPrincipal() + "的用户");
            return Result.buildResult(100003, "没有用户名为" + token.getPrincipal() + "的用户");
        } catch (IncorrectCredentialsException ice) {
            json.put("message", "用户名为：" + token.getPrincipal() + "的用户密码不正确");
            return Result.buildResult(100004, token.getPrincipal() + "的用户密码不正确");
        } catch (LockedAccountException lae) {
            json.put("message", "用户名为：" + token.getPrincipal() + "的用户已被冻结");
            return Result.buildResult(100005, token.getPrincipal() + "的用户已被冻结");
        }
        //  }
        json.put("token", subject.getSession().getId());
        json.put("name", name);
        return Result.buildResult(json);
    }


}
